package com.spboot.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.solr.core.SolrTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spboot.entity.Product;
import com.spboot.mapper.ProductMapper;
import com.spboot.page.PageInfo;
import com.spboot.service.ProductService;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author guocb
 * @since 2020-01-13
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

	@Autowired
	SolrClient solrClient; // solr api

	@Autowired
	SolrTemplate solrTemplate;// springboot solr api

	@Override
	public PageInfo<Product> selectProductSolr(String proName, int pageIndex) {

		// 查询条件构造器
		SolrQuery query = new SolrQuery();
		if (StringUtils.isNotEmpty(proName)) {
			query.set("q", "proName:" + proName);

			// 高亮
			query.addHighlightField("proName");// 添加高亮字段
			query.setHighlightSimplePre("<span style='color:red'>");// 前缀
			query.setHighlightSimplePost("</span>");// 后缀

		} else
			query.set("q", "*:*"); //默认全部

		// 查询添加分页参数
		query.setStart((pageIndex - 1) * 10);
		query.setRows(10);

		//排序
		query.setSort("proNum", ORDER.desc);
		try {
			// 配置文件没有指定core使用
			QueryResponse queryResponse = solrClient.query(query);

			// 高亮结果集 key
			Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();

			// 获取结果集
			SolrDocumentList results = queryResponse.getResults();
			// 总记录数
			long total = results.getNumFound();
			System.out.println("总记录:" + total);
			List<Product> productList = new ArrayList<>();
			for (SolrDocument solrDocument : results) {
				// Product product = new Product();
				// 1.
				// product.setId((int)solrDocument.get("id"));

				// 2.json转换成实体类
				Product product = JSON.parseObject(solrDocument.jsonStr(), Product.class);

				// 高亮结果
				if (highlighting != null) {
					//key id
					Map<String, List<String>> map = highlighting.get(product.getId().toString());
					//key 高亮字段
					String hlproName = map.get("proName").get(0);
					// 设置新的商品名称为高亮结果
					product.setProName(hlproName);
				}

				productList.add(product);
			}

			PageInfo<Product> pageInfo = new PageInfo<>(pageIndex, 10);
			pageInfo.setTotal(total);
			pageInfo.setRecords(productList);
			return pageInfo;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public boolean saveOrUpdateProduct(Product product) {
		try {
			// solrClient.deleteById(id);
			// 添加到数据库
			saveOrUpdate(product);
			// 添加solr
			UpdateResponse response = solrClient.addBean(product);
			solrClient.commit();// 提交solr事物
			return response.getStatus() == 0;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public boolean deleteProductById(Integer id) {
		try {
			removeById(id);
			UpdateResponse response = solrClient.deleteById(id.toString());
			solrClient.commit();// 提交solr事物
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
}
